package com.tsd.core.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.tsd.core.datasource.DynamicDataSource;
import com.tsd.core.utils.ExceptionUtil;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

/**
 * @Description: Mybatis的配置类
 * @Author Luoyc
 * @Date 2019/2/18 10:01
 * @Modefied By:
 */
@Configuration
public class MyBatisConfig {

    public static final Logger LOGGER = LoggerFactory.getLogger(MyBatisConfig.class);

    @Value("${mybatis.config-location}")
    private String configLocation;
    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;
    @Value("${mybatis.type-aliases-package}")
    private String typeAliasesPackage;
    @Value("${mybatis.type-handlers-package}")
    private String typeHandlersPackage;
    @javax.annotation.Resource
    private DruidDataSource masterDataSource;
    @javax.annotation.Resource
    private DynamicDataSource dynamicDataSource;

    @Bean
    @ConditionalOnMissingBean
    //当容器里没有指定的Bean的情况下创建该对象
    public SqlSessionFactoryBean sqlSessionFactoryBean() {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource);
        sqlSessionFactoryBean.setDataSource(dynamicDataSource);
        sqlSessionFactoryBean.setTypeHandlersPackage(typeHandlersPackage);
        //设置mybatis的主配置文件
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(configLocation));
        // 设置mapper映射文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] mapperXml;
        try {
            mapperXml = resolver.getResources(mapperLocations);
            sqlSessionFactoryBean.setMapperLocations(mapperXml);
        } catch (IOException e) {
            LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
        }
        //设置别名包
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        return sqlSessionFactoryBean;
    }
}
